package com.xcj.springai.service.impl;


import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xcj.springai.entity.ChatMessageEntity;
import com.xcj.springai.mapper.ChatMessageMapper;
import com.xcj.springai.service.ChatMessageService;
import com.xcj.springai.vo.ChatHistoryMessageVo;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@RequiredArgsConstructor
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessageEntity> implements ChatMessageService {


    @Override
    public List<ChatHistoryMessageVo> getChatHistoryMessage(Long userId, String conversationId) {
        List<ChatMessageEntity> list = list(new LambdaQueryWrapper<ChatMessageEntity>()
                .eq(ChatMessageEntity::getConversationId, conversationId)
                .eq(ChatMessageEntity::getUserId, userId));
        List<ChatHistoryMessageVo> chatHistoryMessageVos = list.stream().map(v -> {
            ChatHistoryMessageVo chatHistoryMessageVo = new ChatHistoryMessageVo();
            chatHistoryMessageVo.setContents(v.getContent());
            chatHistoryMessageVo.setRoleType(v.getRoleType());
            chatHistoryMessageVo.setTime(v.getCreateTime());
            if (v.getRoleType() != MessageType.USER) {
                if (v.getContent().startsWith("{") && v.getContent().endsWith("}")) {
                    String content = JSONUtil.parseObj(v.getContent()).getStr("contentType");
                    chatHistoryMessageVo.setContentType(content);
                } else {
                    chatHistoryMessageVo.setContentType("ai");
                }
            } else {
                chatHistoryMessageVo.setContentType("question");
            }
            return chatHistoryMessageVo;
        }).toList();
        return chatHistoryMessageVos;
    }
}




